#!/bin/sh

# Check script requirements
if [[ -x "$(npm exec which semver)" ]]; then
  echo "Check verion:"
  TAG_VERSIONNUM=$(npm exec semver $(git tag) | tail -1)
  VERSIONNUM=$(/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "${PROJECT_DIR}/${INFOPLIST_FILE}")
  TAG_PATCH=$(echo $TAG_VERSIONNUM | awk -F "." '{print $3}')
  PATCH=$(echo $VERSIONNUM | awk -F "." '{print $3}')
  NEWPATCH=$(($PATCH + 1))
  NEWVERSIONSTRING=$(echo $VERSIONNUM | awk -F "." '{print $1 "." $2 ".'$NEWPATCH'" }')
  echo "[check-point] Building Version: $NEWVERSIONSTRING"
  if [[ $TAG_PATCH == $PATCH ]]; then
    /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $NEWVERSIONSTRING" "${PROJECT_DIR}/${INFOPLIST_FILE}"
  else
    echo "warning: Version (${VERSIONNUM}) is already ahead of latest git tag (${TAG_VERSIONNUM})"
  fi
else
  echo "Build without updating version"
fi
